package com.function.controller;

import com.function.domin.dto.SignUp2DTO;
import com.function.domin.dto.UserLoginDTO;
import com.function.domin.pojo.Result;
import com.function.domin.pojo.User;
import com.function.domin.vo.UserLoginVO;
import com.function.properties.JwtProperties;
import com.function.service.UserService;
import com.function.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@Slf4j
@RestController
@Api(tags = "用户相关接口")
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 用户注册
     * 发送验证码
     * @param user
     * @return
     */
    @ApiOperation("注册1（发送验证码）")
    @PostMapping("/signUp1")
    public Result signUp1(@RequestBody User user){
        log.info("注册1：{}", user);
        userService.signUp1(user);
        return Result.success();
    }

    /**
     * 用户注册
     * 校验验证码
     * @return
     */
    @ApiOperation("注册1（校验验证码）")
    @PostMapping("/signUp2")
    public Result signUp2(@RequestBody SignUp2DTO signUp2DTO){
        log.info("注册2：{}", signUp2DTO);
        userService.signUp2(signUp2DTO);
        return Result.success();
    }

    /**
     * 用户登录接口
     * @param userLoginDTO
     * @return
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("登录：{}", userLoginDTO);
        //校验用户
        User loginUser = userService.login(userLoginDTO);
        //登录成功，生成令牌
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("id", loginUser.getId());
        //claims.put("username", loginUser.getUsername());
        //claims.put("password", loginUser.getPassword());
        String token = JwtUtil.createJWT(
                jwtProperties.getSignKey(),
                jwtProperties.getExpire(),
                claims);
        //封装VO对象
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(loginUser.getId())
                .username(loginUser.getUsername())
                .emailAccount(loginUser.getEmailAccount())
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }

}
